//
//  NSArray+Safe.m
//  AMHexin
//
//  Created by MacMini on 16/6/16.
//
//

#import "NSArray+Safe.h"
#import <objc/runtime.h>

#define IsIndexSafe index < [self count]

@implementation NSArray(Safe)

-(id)objectAtIndexSafe:(NSUInteger)index
{
    if (index < [self count])
    {
        return [self objectAtIndex:index];
    }
    return nil;
}

@end


@implementation NSMutableArray (Safe)
+ (void)load {
    Method original = class_getClassMethod(self , @selector(replaceObjectAtIndex:withObject:));
    Method swizze = class_getClassMethod(self, @selector(replaceObjectAtIndexSafe:withObject:));
    method_exchangeImplementations(original, swizze);
}
- (void)replaceObjectAtIndexSafe:(NSUInteger)index withObject:(nonnull id)anObject
{
    if (IsIndexSafe && anObject)
    {
        [self replaceObjectAtIndexSafe:index withObject:anObject];
    }
}

- (void)removeObjectAtIndexSafe:(NSUInteger)index
{
    if (IsIndexSafe)
    {
        [self removeObjectAtIndex:index];
    }
}

- (void)insertObjectSafe:(nonnull id)anObject atIndex:(NSUInteger)index
{
    if (IsIndexSafe && anObject)
    {
        [self insertObject:anObject atIndex:index];
    }
}

@end
